<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-rank"></i> {{ seriesType }}系列 训练集管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <el-row>
        <el-col :span="16">
          <div class="handle-box">
            <el-button
              type="primary"
              icon="el-icon-delete"
              class="handle-del mr10"
              @click="delAllSelection"
              >批量删除</el-button
            >
          </div>
          <el-table
            :data="tableData"
            height="600"
            class="table"
            ref="multipleTable"
            :highlight-current-row="true"
            header-cell-class-name="table-header"
            @selection-change="handleSelectionChange"
            @row-click="handleRowClick"
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="title"
              label="曲线名称"
              align="center"
              width="320"
            ></el-table-column>
            <!-- <el-table-column prop="type" label="所属系列" align="center"></el-table-column> -->
            <el-table-column
              prop="userName"
              label="所属用户"
              align="center"
            ></el-table-column>
            <el-table-column label="是否精选" align="center">
              <template slot-scope="scope">
                <el-tag>{{ scope.row.selected == 1 ? "是" : "否" }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="时间"
              width="105"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  icon="el-icon-delete"
                  class="red"
                  @click="handleDelete(scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="8">
          <div
            id="main"
            v-show="isChart"
            class="chart-cur"
            style="width: 390px; height: 600px"
          ></div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { fetchData } from "../../api/index";
export default {
  name: "datatable",
  data() {
    return {
      isChart: false,
      seriesType: "",
      inputValue: "",
      serachType: "用户",
      query: {
        status: "",
        address: "",
        name: "",
        pageIndex: 1,
        pageSize: 10,
      },
      tableData: [],
      multipleSelection: [],
      delList: [],
      editVisible: false,
      pageTotal: 0,
      form: {},
      idx: -1,
      id: -1,
      DEFAULT_VARIANCE: 5.0,
      DEFAULT_NOISE: 1.0,
      lastValue: 0,
      lastVariance: 0,
      initialized: false,
    };
  },

  created() {},

  mounted() {
    this.seriesType = this.$route.query.type;
    this.getTrainList();
    // this.myEchartsAgin();
  },

  watch: {
    $route(to, from) {
      console.log("路由变化");
      this.seriesType = this.$route.query.type;
      this.isChart = false;
      this.getTrainList();
    },
  },

  methods: {
    getTrainList() {
      let that = this;
      let param = { type: this.seriesType };
      this.POST(false, "all_train_record", param, "get", (result) => {
        console.log(result);
        if (result.code == "A00001") {
          let res = result.data;
          result.data.map((item) => {
            item.createTime = that.formatDate(item.createTime * 1000);
          });
          that.tableData = result.data;
        }
      });
    },
    formatDate(date) {
      var date = new Date(date);
      var YY = date.getFullYear() + "-";
      var MM =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      return YY + MM + DD;
    },

    // 触发搜索按钮
    handleSearch() {
      let params = {};
      if (this.serachType == "用户名") {
        params.userName = this.inputValue;
        params.type = 0;
        this.searchUserList("search_user_by_name", params);
      } else {
        params.mobile = this.inputValue;
        this.searchUserList("search_user_by_mobile", params);
      }
    },

    searchUserList(api, param) {
      let that = this;
      this.POST(false, api, param, "get", (result) => {
        console.log(result);
        if (result.code == "A00001") {
          let res = result.data;
          result.data.map((item) => {
            item.createTime = that.formatDate(item.createTime);
          });
          console.log(res);
          console.log("999999");
          that.tableData = result.data;
        }
      });
    },

    // 删除操作
    handleDelete(index, row) {
      let that = this;
      console.log(index, row);
      // 二次确认删除
      this.$confirm("确定要将该曲线移出训练集吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          console.log("index,row");
          let param = {
            recordId: row.recordId,
          };
          console.log(param);
          that.POST(false, "set_is_train", param, "post", (result) => {
            if (result.code == "A00001") {
              that.$message({
                message: "删除成功",
                type: "success",
                duration: 1000,
              });
              that.getTrainList();
            } else {
              that.$message({
                message: "删除失败，请重试",
                type: "error",
                duration: 1000,
              });
            }
          });
        })
        .catch(() => {});
    },

    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleRowClick(val) {
      console.log(val);
      this.isChart = true;
    //   this.myEchartsAgin(val);
    this.getCurveData(val)
    },

    delAllSelection() {
      let that = this;
      console.log("this.multipleSelection");
      console.log(this.multipleSelection);
      let length = this.multipleSelection ? this.multipleSelection.length : 0;
      if (length == 0) {
        that.$message({
          message: "请选择数据项",
          type: "error",
          duration: 1000,
        });
        return;
      }
      let list = [];
      this.multipleSelection.map((item) => {
        list.push(item.recordId);
      });
      let param = { list: list };
      console.log(param);
      that.POST(false, "del_train_list", param, "post", (result) => {
        if (result.code == "A00001") {
          that.$message({
            message: "删除成功",
            type: "success",
            duration: 1000,
          });
          this.multipleSelection = [];
          that.getTrainList();
        } else {
          that.$message({
            message: "删除失败，请重试",
            type: "error",
            duration: 1000,
          });
        }
      });
    },
    getCurveData(val) {
      let param = {
        recordId: val.recordId,
      };
      this.POST(false, "get_record", param, "get", (result) => {
        if (result.code == "A00001") {
          console.log(result);
          this.myEchartsAgin(result.data.data,val);
        }
      });
    },
    myEchartsAgin(detail,val) {
      let _this = this;
      var myChart = this.$echarts.init(document.getElementById("main"));
      //豆温
      var btData = detail.beanTemperatureArray;
      //风温
      var etData = detail.environmentTemperatureArray;
      for (var i = 0; i < etData.length; i++) {
        etData[i] = Number(etData[i]).toFixed(1)
      }
      //火力
      var firData = detail.firepowerArray;
      //风门
      var damData = detail.damperArray;
      //ror
      var ror = this.getRorDatas(btData,detail.timeArray);
      var rorData = this.getShowRorDatas(ror);
      //时间
      var timeData = this.getTimeDatas(detail.timeArray);
      //操作数组
      var events = detail.eventArray;

      var nbtData = this.getBtDatas(detail, ror);
      console.log("豆温", btData);
      let til = val.userName ? "客户：" + val.userName : "";
      let that = this;
      let option = {
        animation: false,
        title: {
          left: "center",
          text: til,
          subtext: "",
        },
        dataZoom: [
          {
            type: "inside",
            disabled: true,
            zoomLock: true,
          },
        ],
        tooltip: {
          trigger: "axis",
          alwaysShowContent: true,
          formatter: function (params, ticket, callback) {
            let eName = "";
            let name = params[0].name;
            if (params[0].dataIndex == btData.length - 2) {
              eName = "结束";
              name = that.dateFormat(
                detail.timeArray[detail.timeArray.length - 1]
              );
            }
            for (var i = 0; i < events.length; i++) {
              let event = events[i];
              if (params[0].dataIndex == event.time) {
                eName = that.getName(event.event);
              }
            }
            let fm = name + " " + eName + "<br />";

            for (var i = 0; i < params.length; i++) {
              fm += params[i].seriesName + "：" + params[i].value;
              if (i < params.length - 1) {
                fm += "<br />";
              }
            }
            return fm;
          },
        },
        xAxis: {
          type: "category",
          splitLine: {
            show: true,
          },
          axisLabel: {
            interval: 59,
            showMaxLabel: true,
          },
          boundaryGap: true,
          data: timeData,
        },
        yAxis: [
          {
            id: 0,
            type: "value",
            axisTick: {
              inside: true,
            },
            splitLine: {
              show: true,
            },
            min: 0,
            max: 300,
          },
          {
            id: 1,
            type: "value",
            axisTick: {
              inside: true,
            },
            splitLine: {
              show: true,
            },
            min: 0,
            max: 120,
          },
        ],
        series: [
          {
            yAxisIndex: 0,
            name: "风温",
            type: "line",
            smooth: true,
            symbol: "circle",
            symbolSize: 1,
            sampling: "average",
            itemStyle: {
              color: "#2688eb",
            },
            stack: "a",
            areaStyle: {},
            data: etData,
          },
          {
            yAxisIndex: 0,
            name: "豆温",
            type: "line",
            smooth: true,
            stack: "b",
            symbol: "circle",
            symbolSize: 1,
            sampling: "average",
            itemStyle: {
              color: "#fb0c1a",
            },
            areaStyle: {},
            data: nbtData,
          },
          {
            yAxisIndex: 0,
            name: "火力",
            type: "line",
            smooth: true,
            symbol: "circle",
            symbolSize: 1,
            sampling: "average",
            itemStyle: {
              color: "#000000",
            },
            data: firData,
          },
          {
            yAxisIndex: 0,
            name: "风门",
            type: "line",
            smooth: true,
            symbol: "circle",
            symbolSize: 1,
            sampling: "average",
            itemStyle: {
              color: "#20c5cc",
            },
            data: damData,
          },
          {
            yAxisIndex: 1,
            name: "ROR",
            type: "line",
            smooth: true,
            symbol: "circle",
            symbolSize: 1,
            sampling: "average",
            itemStyle: {
              color: "#edc72c",
            },
            data: rorData,
          },
        ],
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    },
    getFM(detail, rorData) {},
    getBtDatas(detail, rorData) {
      //豆温
      var btData = detail.beanTemperatureArray;
      //风温
      var etData = detail.environmentTemperatureArray;
      //火力
      var firData = detail.firepowerArray;
      //风门
      var damData = detail.damperArray;
      //时间
      var timeData = detail.timeArray;
      //操作数组
      var events = detail.eventArray;

      var datas = btData;

      for (var i = 0; i < timeData.length; i++) {
        let t = timeData[i];
        let bt = Number(btData[i]).toFixed(1);
        btData[i] = bt
        // let fm =
        //   "豆温：" +
        //   bt +
        //   "<br />" +
        //   "风温：" +
        //   etData[i] +
        //   "<br />" +
        //   "火力：" +
        //   firData[i] +
        //   "<br />" +
        //   "风门：" +
        //   damData[i] +
        //   "<br />" +
        //   "ROR：" +
        //   rorData[i];
        for (var j = 0; j < events.length; j++) {
          let event = events[j];
          if (event.event != 5) {
            if (t == event.time) {
              datas[i] = {
                value: bt,
                symbolSize: 10,
                showAllSymbol: true,
                // tooltip: {
                //   formatter:
                //     "" +
                //     this.dateFormat(t) +
                //     "<br />" +
                //     this.getName(event.event) +
                //     "<br />" +
                //     fm,
                // },
              };
            }
          }
        }
        if (i == timeData.length - 2) {
          datas[i] = {
            value: bt,
            symbolSize: 10,
            showAllSymbol: true,
            // tooltip: {
            //   formatter:
            //     "" +
            //     this.dateFormat(t) +
            //     "<br />" +
            //     this.getName(event.event) +
            //     "<br />" +
            //     fm,
            // },
          };
        }
      }
      return datas;
    },
    getName(type) {
      if (type == 1) {
        return "开始";
      } else if (type == 2) {
        return "转黄";
      } else if (type == 3) {
        return "一爆";
      } else if (type == 4) {
        return "二爆";
      } else {
        return "结束";
      }
    },
    getRorDatas(btData, timeArray) {
      var rorData = [];
      this.DEFAULT_VARIANCE = 5;
      this.DEFAULT_NOISE = 1;
      this.lastValue = 0;
      this.lastVariance = 0;
      this.initialized = false;
      for (var i = 1; i < btData.length; i++) {
        let ror =
          (btData[i] - btData[i - 1]) / (timeArray[i] - timeArray[i - 1]);
        rorData.push(this.filter(ror));
      }
      this.smoothData(rorData,9)
      this.smoothData(rorData,7)
      this.smoothData(rorData,5)
      this.smoothData(rorData,3)
      return rorData;
    },
    smoothData(data, span) {
      if (data.length <= span * 2) {
        return data;
      }
      let length = data.length;
      let r = (span - 1) >> 1;
      for (var i = 1; i <= r; i++) {
        var v = data[i];
        for (var j = 1; j <= i; j++) {
          v += data[i + j] + data[i - j];
        }
        let mean = v / (i * 2 + 1);
        data[i] = mean;
      }
      var sum = data[r] * span;
      for (var i = r + 1; i < length - r; i++) {
        sum = sum - data[i - r - 1] + data[i + r];
        data[i] = sum / span;
      }

      for (var i = length - r; i < length; i++) {
        var v = data[i];
        for (var j = 1; i + j < length; j++) v += data[i + j] + data[i - j];
        var mean = v / ((length - i - 1) * 2 + 1);
        data[i] = mean;
      }
      return data;
    },
    filter(dBt) {
      if (!this.initialized) {
        this.lastValue = dBt;
        this.lastVariance = this.DEFAULT_VARIANCE;

        this.initialized = true;
        return dBt;
      }

      let expValue = this.lastValue;
      let expVariance = this.lastVariance + this.DEFAULT_NOISE;

      let k = expVariance / (expVariance + this.DEFAULT_VARIANCE);
      let value = expValue + k * (dBt - expValue);
      let variance = expVariance - k * this.DEFAULT_VARIANCE;

      this.lastValue = value;
      this.lastVariance = variance;

      return value;
    },
    getShowRorDatas(data) {
      var rorData = [];
      for (var i = 0; i < data.length; i++) {
        let n = Number(data[i] * 60)
        rorData.push(n.toFixed(1))
      }
      return rorData;
    },
    getShowDatas(data) {
      var rorData = [[0, 0]];
      for (var i = 0; i < data.length; i++) {
        if (i % 2 == 1 || i == data.length - 1) {
          rorData.push([i, data[i]]);
        }
      }
      return rorData;
    },
    getTimeDatas(datas) {
      var timeDatas = [];
      var cT = datas[datas.length - 1];
      var maxT = 601;
      while (cT > maxT) {
        maxT += 120;
      }
      for (var i = 0; i < maxT; i++) {
        timeDatas.push(this.dateFormat(i));
      }
      return timeDatas;
    },
    dateFormat(value) {
      var theTime = parseInt(value); // 秒
      var middle = 0; // 分
      if (theTime >= 60) {
        middle = parseInt(theTime / 60);
        theTime = parseInt(theTime % 60);
        if (middle >= 60) {
          middle = parseInt(middle % 60);
        }
      }
      var result = parseInt(theTime);
      if (result < 10) {
        result = "0" + result;
      }
      if (middle > 0) {
        result = "" + parseInt(middle) + ":" + result;
      } else {
        result = "00:" + result;
      }
      return result;
    },
  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
.chart-cur {
  margin-top: 60px;
}
</style>
